package com.baidu.ota.utils;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.otasdk.ota.Constants;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

public class DeviceUtil {
    private static String mac;

    public static String getIMei(Context context) {
        TelephonyManager mgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (mgr == null) {
            Log.e(Constants.TAG, "get IMEI error");
            throw new RuntimeException("get IMEI fail");
        }
        String imei = mgr.getDeviceId();
        if (imei == null) {
            imei = "null";
        }
        return imei;
    }

    public static String getMac(Context context) {
        if (!TextUtils.isEmpty(mac)) {
            return mac;
        }
        try {
            mac = getMacAddress(context);

            // 把冒号去掉，平台认为是特殊字符
            mac = mac.replace(":", "");
        } catch (Exception e) {
            mac = "null";
        }
        return mac;
    }

    private static String getMacAddress(Context context) {
        String mac = "";
        if (context == null) {
            return mac;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            mac = getEthMacAddress();
            if (TextUtils.isEmpty(mac)) {
                try {
                    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                    if (wifiManager != null) {
                        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                        if (wifiInfo != null) {
                            mac = wifiInfo.getMacAddress();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            List<NetworkInterface> networkInterfaces = new ArrayList<>();
            try {
                networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (networkInterfaces != null && !networkInterfaces.isEmpty()) {
                for (NetworkInterface networkInterface : networkInterfaces) {
                    if (!"wlan0".equalsIgnoreCase(networkInterface.getName())) {
                        continue;
                    }
                    byte[] macBytes = null;
                    try {
                        macBytes = networkInterface.getHardwareAddress();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (macBytes == null) {
                        break;
                    }
                    StringBuilder sb = new StringBuilder();
                    for (byte b : macBytes) {
                        sb.append(String.format(Locale.ROOT, "%02X:", b));
                    }
                    if (sb.length() > 0) {
                        sb.deleteCharAt(sb.length() - 1);
                    }
                    mac = sb.toString();
                    break;
                }
            }
        }
        return mac;
    }

    private static String getEthMacAddress() {
        Reader reader = null;
        StringBuilder stringBuilder = new StringBuilder();
        String mac = null;
        try {
            char[] buffer = new char[20];
            int charRead;
            reader = new InputStreamReader(new FileInputStream("/sys/class/net/eth0/address"));
            while ((charRead = reader.read(buffer)) != -1) {
                boolean is = (charRead == buffer.length) && (buffer[buffer.length - 1] != '\r');
                if (!is) {
                    for (int i = 0; i < charRead; ++i) {
                        if (buffer[i] != '\r') {
                            stringBuilder.append(buffer[i]);
                        }
                    }
                }
                mac = stringBuilder.toString().trim();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {

                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return mac;
    }
}
